package org.lib.data.user.controller;

import java.util.Objects;

import javax.validation.constraints.NotBlank;

import org.lib.data.user.api.dto.AddUserDTO;
import org.lib.data.user.api.dto.UpdateUserDTO;
import org.lib.data.user.api.feign.UserFeign;
import org.lib.data.user.api.vo.UserVO;
import org.lib.data.user.entity.User;
import org.lib.data.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RestController;

import lombok.extern.slf4j.Slf4j;

@RestController
@Slf4j
public class UserController implements UserFeign {

	@Autowired
	private UserService userService;
	
	@Override
	public Long addUser(@Validated AddUserDTO dto) {
		// 入参校验，TODO
		log.info("添加用户开始");
		return userService.addUser(dto);
	}

	@Override
	public UserVO getUser(@NotBlank(message="id不能为空") Long id) {
		User user = userService.getById(id);
		if (Objects.isNull(user)) {
			// 没有找到用户
			return null;
		}
		
		log.debug("查询到的user={}", user);
		UserVO uvo = new UserVO(user.getId(), user.getNickName(), user.getEmail(), user.getPhone(), 
				user.getName(), user.getSex(), user.getAge(),
				user.getCreateTime(), user.getUpdateTime());
		log.info("返回uvo={}", uvo);
		return uvo;
	}

	@Override
	public Boolean delUser(Long id) {
		return userService.delById(id);
	}

	@Override
	public UserVO getUserByEmail(String email) {
		User user = userService.getByEmail(email);
		if (Objects.isNull(user)) {
			// 没有找到用户
			return null;
		}
		
		UserVO uvo = new UserVO(user.getId(), user.getNickName(), user.getEmail(), user.getPhone(), 
				user.getName(), user.getSex(), user.getAge(),
				user.getCreateTime(), user.getUpdateTime());
		return uvo;
	}

	@Override
	public UserVO getUserByPhone(String phone) {
		User user = userService.getByPhone(phone);
		if (Objects.isNull(user)) {
			// 没有找到用户
			return null;
		}
		
		UserVO uvo = new UserVO(user.getId(), user.getNickName(), user.getEmail(), user.getPhone(), 
				user.getName(), user.getSex(), user.getAge(),
				user.getCreateTime(), user.getUpdateTime());
		return uvo;
	}

	@Override
	public UserVO updateUser(UpdateUserDTO dto) {
		User user = userService.updateUser(dto);
		if (Objects.isNull(user)) {
			// 没有找到用户
			return null;
		}
		
		UserVO uvo = new UserVO(user.getId(), user.getNickName(), user.getEmail(), user.getPhone(), 
				user.getName(), user.getSex(), user.getAge(),
				user.getCreateTime(), user.getUpdateTime());
		return uvo;
	}

}
